/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AnswerFrm.java
 *
 * Created on 2011-11-24, 10:20:21
 */
package com.edu.kamai.client;

import com.edu.kamai.client.control.paperAnswerControl;
import com.edu.kamai.client.control.paperControl;
import com.edu.kamai.client.control.scoreControl;
import com.edu.kamai.client.download.fileDownload;
import com.edu.kamai.config.Constant;
import com.edu.kamai.utility.FileName;
import com.edu.kamai.webservice.paper.Paper;
import com.edu.kamai.webservice.paperanswer.PaperAnswer;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author xyzhu
 */
public class AnswerFrm extends javax.swing.JFrame {

    /** Creates new form AnswerFrm */
    public AnswerFrm(String tn) {
        initComponents();
        setNet();
        initPending();
        teacherName = tn;
    }
    
    private void showMessage(int ans,String msg){
        if(ans == 1){
            javax.swing.JOptionPane.showMessageDialog(this, msg, "Done", ans);
        }else{
            javax.swing.JOptionPane.showMessageDialog(this, msg, "Error", ans);
        }
    }
    
    private void setNet(){
        try{
            InputStream in = getClass().getResourceAsStream(Constant.netiniFilePath);
            Scanner scan = new Scanner(in);
            List<String> netList = new ArrayList<String>();
            
            while(scan.hasNextLine()){
                String line = scan.nextLine();
                if(!line.equals("")){
                    if(!line.startsWith("#")){
                        netList.add(line);
                    }
                }
            }
            paperControl.setNetList(netList);
            paperAnswerControl.setNetList(netList);
            scoreControl.setNetList(netList);
            scan.close();
            in.close();
        }catch(Exception ex){
            ex.printStackTrace();
            //Control.setNetList(new ArrayList<String>());
        }
        paperControl.setServer();
        paperAnswerControl.setServer();
        scoreControl.setServer();
    }
    
    private void initPending(){
        pending = paperAnswerControl.checkPendingAnswer();
        myDefaultTableModel model = new myDefaultTableModel();
        TA_Pending.setModel(model);
        model.addColumn("Answer ID");
        model.addColumn("Contest ID");
        model.addColumn("Paper ID");
        model.addColumn("Paper Type");
        model.addColumn("Student ID");
        if(pending != null){
            for(int i=0;i<pending.size();i++){
                PaperAnswer tmp = pending.get(i);
                String aid = String.valueOf(tmp.getAnswerId());
                String cid = String.valueOf(tmp.getContestId());
                String pid = String.valueOf(tmp.getPaperId());
                String prole = Constant.paperRoleTable[tmp.getPaperRole()];
                String studnetID = tmp.getUserId();
                model.insertRow(i, new Object[]{aid,cid,pid,prole,studnetID});
            }
        }
    }
    
    private String downloadPaper(String path){
        String url = Constant.urlAddress + "kamai_edu";
        url += path;
        int pos = path.lastIndexOf("/") + 1;
        String filename = FileName.getDefaultKamaiFolder() + path.substring(pos);
        fileDownload fd = new fileDownload(url, filename);
        fd.start();
        return filename;
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        TA_Pending = new javax.swing.JTable();
        B_Judge = new javax.swing.JButton();
        TF_Score = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        TA_Pending.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        TA_Pending.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TA_PendingMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(TA_Pending);

        B_Judge.setText("Judge");
        B_Judge.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_JudgeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 418, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(TF_Score, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
                    .addComponent(B_Judge, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(15, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(TF_Score, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(B_Judge)
                        .addGap(130, 130, 130))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void openAnswer(){
        int selectPendingRow = TA_Pending.getSelectedRow();
        PaperAnswer answer = pending.get(selectPendingRow);
        String answerPaperPath = answer.getPaperPath();
        String downloadAPP = downloadPaper(answerPaperPath);
        
        int pid = answer.getPaperId();
        int rid = answer.getPaperRole();
        Paper paper = paperControl.findPaperByIDAndRole(rid, pid);
        String paperPath = paper.getPaperPath();
        String downloadPP = downloadPaper(paperPath);
        
        if(rid == Constant.WRITING_PAPER_ID){
            WritingFrm wFrm = new WritingFrm(teacherName,downloadPP,downloadAPP);
            wFrm.setVisible(true);
        }else if(rid == Constant.READING_PAPER_ID){
            
        }else if(rid == Constant.SPEAKING_PAPER_ID){
            
        }else if(rid == Constant.LISTENING_PAPER_ID){
            
        }
    }
    private void B_JudgeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_JudgeActionPerformed
        // TODO add your handling code here:
        int selectPendingRow = TA_Pending.getSelectedRow();
        if(-1 == selectPendingRow){
            showMessage(0,"no selected row");
            return;
        }
        int score = Integer.parseInt(TF_Score.getText());
        int aid = pending.get(selectPendingRow).getAnswerId();
        
        System.out.println("aid========:" + aid);
        int ans = paperAnswerControl.updateSocre(aid, teacherName, score);
        showMessage(ans, paperAnswerControl.getMessage());
        
        int contestID = pending.get(selectPendingRow).getContestId();
        String userID = pending.get(selectPendingRow).getUserId();
        int finishTime = pending.get(selectPendingRow).getFinishTime();
        
        int ans1 = scoreControl.updateScoreByContestIDAndStudentID(contestID, 
                userID, score, finishTime, Constant.EnglishContest);
        
       showMessage(ans1, scoreControl.getMessage());
                
    }//GEN-LAST:event_B_JudgeActionPerformed

    private void TA_PendingMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TA_PendingMouseClicked
        // TODO add your handling code here:
        if(evt.getClickCount() == 2){
            openAnswer();
        }
    }//GEN-LAST:event_TA_PendingMouseClicked

    /**
     * @param args the command line arguments
     */
    
    
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AnswerFrm(null).setVisible(true);
            }
        });
    }
    
    private List<PaperAnswer> pending;
    private String teacherName;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton B_Judge;
    private javax.swing.JTable TA_Pending;
    private javax.swing.JTextField TF_Score;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
